#include <stdlib.h>		/* for malloc */
#include <strings.h>	/* for strcmp, strlen, strcpy */
#include "hoc.h"		/* for Symbol_t */

/* External definitions */
extern int execerror(const char*, const char*);

/* Prototype Functions */
void *emalloc(unsigned int);

/* Global Variables */
static Symbol_t* symlist = NULL;	/* Symbol table; linked list */


/* Find str in symbol table */
Symbol_t* lookup(const char *ptr_cstr) {
	Symbol_t* ptr_sym;

	for ( ptr_sym = symlist; ptr_sym != NULL; ptr_sym = ptr_sym->ptr_next ) {
		if ( strcmp( ptr_sym->ptr_cname, ptr_cstr) == 0 ) {
			return ptr_sym;
		}
	}
	return NULL;	/* NULL ==> Not Found */
}

/* Install cname in symbol table */
Symbol_t* install(const char *ptr_cname, int itype, double dvalue) {
	Symbol_t* ptr_sym;

	/* Reserve space for new node */
	ptr_sym = (Symbol_t*) emalloc(sizeof(Symbol_t));
	ptr_sym->ptr_cname = (char *)emalloc(strlen(ptr_cname)+1);	/* +1 for '\0' */

	/* Make the new node */
	strcpy(ptr_sym->ptr_cname, ptr_cname);
	ptr_sym->itype = itype;
	ptr_sym->u.dval = dvalue;

	/* Place the new node at the front of the list */
	ptr_sym->ptr_next = symlist;
	symlist = ptr_sym;

	return ptr_sym;
}

/* Check return from malloc */
void *emalloc(unsigned int isize) {
	void* ptr;
	ptr = malloc(isize);
	if ( ptr == NULL ) {
		execerror("out of memory", NULL);
	}
	return ptr;
}
